import os
import sys
from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QTimer

# 导入窗体内容
from design.captchaDlg import *

from common.logger import logger
from common.retcode import RetCode
from common.utils import get_file_size_str, center_window_on_screen
from api.login import LoginAction

# 创建 MainWin 类并传入Ui_MainWindow
class CaptchaDlg(QDialog, Ui_CaptchaDlg):
	def __init__(self, parent=None):
		super(CaptchaDlg, self).__init__(parent)
		self.setupUi(self)
		center_window_on_screen(self)

		self.toolButtonRefreshCaptcha.clicked.connect(self.onClickedRefreshCaptcha)
		self.pushButtonSubmit.clicked.connect(self.onClickedSubmit)

		self._sess_wp = None
		self._captcha_text = None

	def reset(self, sess_wp, img_data):
		self.lineEditCaptcha.setText('')
		self._sess_wp = sess_wp
		self.saveAndRefreshCaptcha(img_data)

	def saveAndRefreshCaptcha(self, img_data):
		img_path = self.getCaptchaSavePath()
		img_dir = os.path.dirname(img_path)
		if not os.path.isdir(img_dir):
			os.mkdir(img_dir)
		with open(img_path, 'wb') as f:
			f.write(img_data)
			QTimer.singleShot(1, lambda : self.labelCaptcha.setPixmap(QPixmap(img_path)))

	def getCaptchaSavePath(self):
		return os.path.dirname(sys.argv[0]) + os.sep + 'resources' + os.sep + 'captcha.png'

	def onClickedRefreshCaptcha(self):
		login_action = LoginAction(self._sess_wp)
		img_data = login_action.refreshCaptcha()
		self.saveAndRefreshCaptcha(img_data)
			
	def onClickedSubmit(self):
		img_path = self.getCaptchaSavePath()
		os.remove(img_path)

		self._captcha_text = self.lineEditCaptcha.text()

		self.accept()

	def get_captcha_text(self):
		return self._captcha_text